package com.itany.book.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itany.constant.Constant;
import com.itany.exception.ManagerUserExistsException;
import com.itany.exception.RequestParamsException;
import com.itany.exception.WrongUsernameOrPasswordException;
import com.itany.mapper.ManagerUserMapper;
import com.itany.mapper.ManagerUserRoleMapper;
import com.itany.pojo.ManagerUser;
import com.itany.pojo.Permission;
import com.itany.pojo.Role;
import com.itany.pojo.Supplier;
import com.itany.service.ManagerUserService;
import com.itany.utils.StringUtils;
import com.itany.vo.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public class ManagerUserServiceImpl implements ManagerUserService {

    @Autowired
    ManagerUserMapper managerUserMapper;

    @Autowired
    ManagerUserRoleMapper managerUserRoleMapper;

    /**
     * 添加管理员
     *
     * @param username     角色名称
     * @param password 管理员密码
     * @param supplierId 如果为null,为平台方；否则为对应的供应商（默认为平台方）
     * @param roles    管理员角色
     */
    @Override
    public void addManagerUser(String username, String password,String supplierId, Integer[] roles) throws RequestParamsException,
            ManagerUserExistsException {
        if(StrUtil.isBlankIfStr(username)||StrUtil.isBlankIfStr(password)||roles.length == 0){
            throw new RequestParamsException("请求参数缺失");
        }
        ManagerUser managerUser = managerUserMapper.selectByName(username);
        if(managerUser!=null){
            throw new ManagerUserExistsException("管理员姓名不能重复");
        }
         managerUser = new ManagerUser();
        managerUser.setUsername(username);
        managerUser.setPassword(SecureUtil.md5(password));
        if(!StrUtil.isBlankIfStr(supplierId)){
            Integer supplierIdInt;
            try {
                supplierIdInt = Integer.parseInt(supplierId);
            } catch (NumberFormatException e) {
                throw new RequestParamsException("请求参数格式错误");
            }
            Supplier supplier = new Supplier();
            supplier.setId(supplierIdInt);
            managerUser.setSupplier(supplier);
        }

        managerUserMapper.insertManagerUser(managerUser);
        Integer managerUserId = managerUser.getId();
        for (Integer roleId:roles) {
            managerUserRoleMapper.insertManagerUserRole(managerUserId,roleId);
        }
    }


    /**
     * 修改管理员
     *
     * @param id     角色id
     * @param username     角色名称
     * @param password 管理员密码
     * @param supplierId 如果为null,为平台方；否则为对应的供应商（默认为平台方）
     * @param roles    管理员角色
     */
    @Override
    public void modifyManagerUser(String id,String username, String password,String supplierId, Integer[] roles) throws RequestParamsException,
            ManagerUserExistsException {
        if(StrUtil.isBlankIfStr(id)){
            throw new RequestParamsException("请求参数缺失");
        }
        Integer idInt;
        try {
            idInt = Integer.parseInt(id);
        } catch (NumberFormatException e) {
            throw new RequestParamsException("请求参数格式错误");
        }
        ManagerUser managerUser = managerUserMapper.selectByName(username);
        if(managerUser!=null&&!managerUser.getId().equals(idInt)){
            throw new ManagerUserExistsException("管理员姓名不能重复");
        }
         managerUser = new ManagerUser();
        managerUser.setId(idInt);
        managerUser.setUsername(username);
        if(password != null){
            managerUser.setPassword(SecureUtil.md5(password));
        }
        if(!StrUtil.isBlankIfStr(supplierId)){
            Integer supplierIdInt;
            try {
                supplierIdInt = Integer.parseInt(supplierId);
            } catch (NumberFormatException e) {
                throw new RequestParamsException("请求参数的格式错误");
            }
            Supplier supplier = new Supplier();
            supplier.setId(supplierIdInt);
            managerUser.setSupplier(supplier);
        }

        managerUserMapper.updateManagerUser(managerUser);
        if(roles.length != 0){
            managerUserRoleMapper.deleteByUserId(idInt);
            for (Integer roleId:roles) {
                managerUserRoleMapper.insertManagerUserRole(idInt,roleId);
            }
        }
    }


    /**
     * 分页查找所有管理员
     * @param page 页数
     * @param rows 每页数据条数
     * @return
     * @throws RequestParamsException
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public PageInfo<ManagerUser> findAll(Integer page, Integer rows,String managernameKey) throws RequestParamsException {
        PageHelper.startPage(page, rows);
        List<ManagerUser> list;
        list = managerUserMapper.selectAll(StringUtils.escapeStr(managernameKey));
        for (ManagerUser managerUser:list) {
            List<Role> roles = managerUserRoleMapper.selectByUserId(managerUser.getId());
            managerUser.setRoles(roles);
        }
        return new PageInfo<>(list);
    }

    /**
     * 管理员后台登录
     *
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public ManagerUser login(String username, String password) throws RequestParamsException, WrongUsernameOrPasswordException {
        if(StrUtil.isBlankIfStr(username)||StrUtil.isBlankIfStr(password)){
            throw new RequestParamsException("请求参数缺失");
        }
        ManagerUser managerUser = managerUserMapper.selectByUsernameAndPassword(username, SecureUtil.md5(password));
        if(managerUser == null){
            throw new WrongUsernameOrPasswordException("用户名或密码错误");
        }
        return managerUser;
    }

    /**
     * 动态生成导航菜单
     *
     * @param managerUserId
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public List<Menu> generateMenus(String managerUserId) throws RequestParamsException {
        if(StrUtil.isBlankIfStr(managerUserId)){
            throw new RequestParamsException("请求参数错误");
        }
        Integer managerUserIdInt;
        try {
            managerUserIdInt = Integer.parseInt(managerUserId);
        } catch (NumberFormatException e) {
            throw new RequestParamsException("请求参数格式错误");
        }
        List<Menu> rootMenus = managerUserMapper.selectPermissions(managerUserIdInt, Constant.ROOT_PERMISSION);
        for (Menu rootMenu:rootMenus) {
            rootMenu.setIcon(Constant.ROOT_MENU_ICON);
            List<Menu> sonMenus = managerUserMapper.selectPermissions(managerUserIdInt, rootMenu.getMenuid());
            for (Menu sonMenu:sonMenus) {
                sonMenu.setIcon(Constant.SON_MENU_ICON);
            }
            rootMenu.setMenus(sonMenus);
        }
        return rootMenus;
    }

    /**
     * 修改密码
     *
     * @param newpass       新密码
     * @param managerUserId 登录管理员id
     */
    @Override
    public void modifyPassword(String newpass, String managerUserId) throws RequestParamsException {
        if(StrUtil.isBlankIfStr(newpass)||StrUtil.isBlankIfStr(managerUserId)){
            throw new RequestParamsException("请求参数缺失");
        }
       Integer managerUserIdInt;
        try {
            managerUserIdInt = Integer.parseInt(managerUserId);
        } catch (NumberFormatException e) {
            throw new RequestParamsException("请求参数格式错误");
        }
        managerUserMapper.updatePassword(SecureUtil.md5(newpass),managerUserIdInt);
    }

}
